package uk.org.wookey.jpet;

import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

public class DbAccessHelper extends AbstractTableModel {
	private static final long serialVersionUID = 1L;
	private MySqlDb dbh;
	private ArrayList<String> tables;
	private ArrayList<DbColumn> columns;
	private ArrayList<ArrayList> rows;
	
	public DbAccessHelper(MySqlDb dbh) {
		this.dbh = dbh;
		tables = new ArrayList<String>();
		columns = new ArrayList<DbColumn>();
		
		rows = new ArrayList<ArrayList>();
	}
	
	public void addTable(String tableName) {
		addTable(tableName, dbh.getColumnNames(tableName));
	}
	
	public void addTable(String tableName, String[] newColumns) {
		boolean tablePresent = false;
		
		for (String table: tables) {
			if (table == tableName) {
				tablePresent = true;
				break;
			}
		}
		
		if (!tablePresent) {
			tables.add(tableName);
		}
		
		for (String column: newColumns) {
			System.out.println("COLUMN: " + column);

			DbColumn newCol = new DbColumn(tableName, column, "???");
			boolean columnPresent = false;
			
			for (DbColumn col: columns) {
				if (col.equals(newCol)) {
					columnPresent = true;
					break;
				}
			}
			
			if (!columnPresent) {
				columns.add(newCol);
			}
		}
	}
	
	public String buildQuery() {
		StringBuilder res = new StringBuilder();
		
		if (columns.size() == 0) {
			return null;
		}
		
		res.append("SELECT ");
		res.append(columns.remove(0).toSql());
		
		for (DbColumn col: columns) {
			res.append(", ");
			res.append(col.toSql());
		}
		
		if (tables.size() > 0) {
			res.append(" FROM ");
			res.append(tables.remove(0));
			
			for (String table: tables) {
				res.append(", ");
				res.append(table);
			}
		}
		
		return res.toString();
	}
	
	public void dump() {
		System.out.println("Query involves the following tables:");
		for (String table: tables) {
			System.out.println("  " + table);
		}
	
		System.out.println("Query involves the following columns:");
		for (DbColumn col: columns) {
			System.out.println("  " + col.toSql());
		}
		
		System.out.println("SQL: " + buildQuery());
	}

	@Override
	public int getColumnCount() {
		return columns.size();
	}

	@Override
	public int getRowCount() {
		return 0;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		return null;
	}
}
